package com.hyts.agent.attach.handle;

import com.hyts.agent.attach.domain.AttachModel;
import com.hyts.agent.attach.domain.JvmMetadataModel;
import com.sun.tools.attach.*;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

/**
 * project-name:coffice-toolbox
 * package-name:com.hyts.agent.attach.handle
 * author:Libo/Alex
 * create-date:2019-06-30 21:54
 * copyright:libo-hyts-github
 * email:libo2dev@aliyun.com
 * description:此类主要用于:
 */
public class AttachMetadataHandle {



    /**
     * attach 操作 获取加载loadAgent相关对于的agent.jar包到
     * 对于的jvm虚拟机
     * @param attachModel
     */
    public static void attach(AttachModel attachModel){
        //判断attach对象
        if(attachModel != null){
            if(attachModel.getAgentJarPath() != null && Files.exists(Paths.get(attachModel.getAgentJarPath()))){
                if(attachModel.getTargetJvmPid()  != null && attachModel.getTargetJvmPid() <= 0 ){
                    VirtualMachine vm = null;
                    try {
                        vm = VirtualMachine.attach(attachModel.getTargetJvmPid()+"");
                        vm.loadAgent(attachModel.getAgentJarPath(),"start load the agent jar");
                    } catch (AttachNotSupportedException | AgentLoadException |
                            AgentInitializationException |IOException e) {
                        e.printStackTrace();
                    }finally {
                        if(vm != null) {
                            try {
                                vm.detach();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }
            }
        }
    }

    /**
     * 获取jvm 信息列表
     * @return
     */
    public  List<JvmMetadataModel> getJvmList(){
       return VirtualMachine.list().parallelStream().
               map(param->JvmMetadataModel.builder().id(param.id()).
                          displayName(param.displayName()).provider(param.provider()).build()
        ).collect(Collectors.toList());
    }
    /**
     * 输出操作服务
     * @param param
     */
    private void accept(JvmMetadataModel param) {
        //agentLogger.info(param.toString());
        System.out.println(param.toString());
    }

    public static void main(String[] args){
        AttachMetadataHandle attachMetadataHandle = new AttachMetadataHandle();
        attachMetadataHandle.getJvmList().forEach(attachMetadataHandle::accept);
    }
}
